package com.example.k8s.hello.service.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.k8s.hello.service.sys.dao.SysConfigDao;
import com.example.k8s.hello.service.sys.service.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import com.example.k8s.hello.common.exception.ApiExEnum;
import com.example.k8s.hello.common.utils.JsonUtils;
import com.example.k8s.hello.common.bean.Page;
import com.example.k8s.hello.bean.sys.entity.SysConfigEntity;
import com.example.k8s.hello.bean.sys.query.SysConfigQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigDao, SysConfigEntity> implements SysConfigService {

	@Override
	public Page queryPage(SysConfigQuery query, Page page) {
		String paramKey = query.getParamKey();

		return this.page(
			page,
				Wrappers.lambdaQuery(SysConfigEntity.class)
				.like(StringUtils.isNotBlank(paramKey),SysConfigEntity::getParamKey, paramKey)
				.eq(SysConfigEntity::getStatus, 1)
		);
	}

	@Override
	public void saveConfig(SysConfigEntity config) {
		check(config);
		this.save(config);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysConfigEntity config) {
		check(config);
		this.updateById(config);
	}

	private void check(SysConfigEntity config) {
		ApiExEnum.A0010.assertTrue(!baseMapper.exists(Wrappers.lambdaQuery(SysConfigEntity.class)
				.ne(config.getId() != null, SysConfigEntity::getId, config.getId())
				.eq(SysConfigEntity::getParamKey, config.getParamKey())), "paramValue重复，无法保存");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateValueByKey(String key, String value) {
		baseMapper.updateValueByKey(key, value);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatch(Long[] ids) {
		for(Long id : ids){
			SysConfigEntity config = this.getById(id);
		}

		this.removeByIds(Arrays.asList(ids));
	}

	@Override
	public String getValue(String key) {
		SysConfigEntity config = baseMapper.queryByKey(key);
		return config == null ? null : config.getParamValue();
	}
	
	@Override
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if(StringUtils.isNotBlank(value)){
			return JsonUtils.parseObject(value, clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException("获取参数失败", e);
		}
	}

	@Override
	public SysConfigEntity infoByKey(String paramKey) {
		return baseMapper.selectOne(Wrappers.lambdaQuery(SysConfigEntity.class).eq(SysConfigEntity::getParamKey, paramKey));
	}
}
